var moment = require('moment');
var dates = require("../common/dates");

var async = require("async");
var memberOrdersServiceNative = require("../services/MemberOrdersService");
var errorHandler = require('../common/errorHandler');
var MemberOrdersController = {
		getMemberOrders: function (req, res, next) {
            var memberOrdersService = errorHandler.errorToResponse(req, res, memberOrdersServiceNative);
			var memberId = req.params.id;
			var month = req.query.month;
			if (!month) {
				month = moment().format("YYYY-MM");
			}

			memberOrdersService.getOrderListByMember(memberId, dates.monthStart(month, 2), dates.monthEnd(dates.monthStart(month, 0)), function (err, orders) {
				var orderIds = [];
				for (var i in orders) {
					orderIds.push(orders[i].id);
				}
				memberOrdersService.getOrderItemsByOrderIds(orderIds, function (err, orderItems) {
					for (var i in orders) {
						orders[i].orderitem = [];
						for (var j in orderItems) {
							if (orders[i].id == orderItems[j].orders_id) {
								orders[i].orderitem.push(orderItems[j].inventoryname);
							}
						}
					}
					res.send({count: orders.length, orders: orders})
				})
			});


		},

		getOrderInfo: function (req, res, next) {
		    var memberOrdersService = errorHandler.errorToResponse(req, res, memberOrdersServiceNative);

			var orderId = req.params.id;
			var order = {};
			async.series([
				function (cb) {
					memberOrdersService.getOrderInfo(orderId, function (err, data) {
						order = data;
						cb(err, data);
					})
				},
				function (cb) {
					memberOrdersService.getOrderItems(orderId, function (err, items) {
						order.items = items;
						cb(err, items);
					})
				},
				function (cb) {
					memberOrdersService.getOrderPayments(order.checkout_id, function (err, payments) {
						order.checkout = {};
						order.checkout.payments = payments;
						cb(err, payments);
					})
				}
			], function (err, data) {
				if (err) {
					return res.status(400).json({error: "参数错误"})
				}
				res.send(order);
			})


		}
	}
	;
module.exports = MemberOrdersController;
